package com.electric.qrapp.utils.function

import android.Manifest
import android.content.Context
import android.content.Intent
import android.provider.Settings
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.MutableLiveData
import com.electric.qrapp.utils.system.Constants
import com.electric.qrapp.utils.system.showToast
import com.permissionx.guolindev.PermissionX

/**
 *@author created by WA03675
 *@date  2022-03-21 16:44
 *@des
 */

fun startLocation(context: Context,liveData: MutableLiveData<String>) {
    PermissionX.init(context as FragmentActivity)
        .permissions(
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
        )
        .onExplainRequestReason { scope, deniedList ->
            scope.showRequestReasonDialog(
                deniedList,
                "您必须先同意此权限才能使用App服务",
                "好的"
            )
        }
        .request { allGranted, _, _ ->
            if (allGranted) {
                if (GPSUtils.getInstance(context).isLocationProviderEnabled) {
                    showLocationWithToast(context,liveData)
                } else {
                    requestLocation(context)
                }
            } else {
                showToast(msg = "请先同意权限")
            }
        }
}

private fun showLocationWithToast(context: Context,liveData: MutableLiveData<String>) {
    val location = GPSUtils.getInstance(context).location
    if(location==null){
        showToast(msg = "定位失败,请稍后重试!")
        return;
    }
    liveData.postValue("${location.longitude},${location.latitude}")
}

/**
 * 检查地理位置开关是否打开，如果未打开，则提示用户打开地理位置开关。
 * 如果已打开，则显示地理位置；如果被拒绝，直接关闭窗口。
 */
private fun requestLocation(context: Context) {
    val message = "本应用需要获取地理位置，请打开获取位置的开关"
    val alertDialog = AlertDialog.Builder(context).setMessage(message).setCancelable(false)
        .setPositiveButton(android.R.string.ok)
        { dialog, _ ->
            dialog.dismiss()
            gotoSysLocationSettingsPage(context)
        }
        .setNegativeButton(android.R.string.cancel) { dialog, _ -> dialog.dismiss() }
        .create()
    alertDialog.show()
}

private fun gotoSysLocationSettingsPage(context: Context) {
    val intent = Intent()
    intent.action = Settings.ACTION_LOCATION_SOURCE_SETTINGS
    (context as FragmentActivity).startActivityForResult(intent, Constants.REQ_LOCATION)
}